<template>
  <table-row-detail-dialog ref="detailDialog" @confirm="handleUserConfirm">
    <div class="dialog-body">
      <el-form ref="form" label-width="90px" :model="formData" :rules="rules">
        <!-- <form-item-group :form-data="formData" ref="formGroup"> -->
        <el-form-item label="登录名" prop="userName">
          <el-input
            v-model.trim="formData.userName"
            type="text"
            :disabled="dialogType === 'edit'"
            @focus="nameFlag = false"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="realName">
          <el-input v-model.trim="formData.realName" type="text"> </el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="tel">
          <el-input
            v-model="formData.tel"
            type="text"
            maxlength="11"
            required
            @focus="telFlag = false"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="设置密码"
          prop="passwd"
          v-if="dialogType === 'add'"
        >
          <el-input
            v-model="formData.passwd"
            type="password"
            placeholder="至少8位且必有数字、特殊字符、字母"
            clearable
            autocomplete="new-password"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="重复密码"
          prop="repeatPass"
          v-if="dialogType === 'add'"
        >
          <el-input
            v-model="formData.repeatPass"
            type="password"
            clearable
            autocomplete="new-password"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="所在机构" prop="organid">
          <el-cascader
            v-model="formData.organid"
            :options="organOption"
            :props="organProps"
            style="width: 100%"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="选择角色" prop="role">
          <el-select
            v-model="formData.role"
            multiple
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="op in roleOption"
              :key="op.roleId"
              :label="op.roleName"
              :value="op.roleId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户描述" prop="description">
          <el-input
            v-model="formData.description"
            class="form-item-input"
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="用户状态" prop="enable">
          <el-switch
            v-model="formData.enable"
            class="form-item-input"
            active-color="#67C23A"
            inactive-color="#F56C6C"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          ></el-switch>
        </el-form-item>
      </el-form>
    </div>
    <!-- <template #footer>
      <el-button
        type="primary"
        :disabled="
          ((!nameCheck || !telCheck) && dialogType === 'add') ||
          (!telCheck && dialogType === 'edit')
        "
        @click="handleUserConfirm"
        style="width: 18%"
        >确 认</el-button
      >
      <el-button @click="handleCancel" style="width: 20%">取 消</el-button>
    </template> -->
  </table-row-detail-dialog>
</template>

<script>
import TableRowDetailDialog from '@/components/TableRowDetailDialog/index';
import FormItemGroup from '@/components/FormItemGroup/index';

import { arrayToTree } from '@/utils';
import { phoneValid, usernameValid } from '@/api/serve/setting';
import { add, edit, detail, setUserRole, userRoles } from '@/api/system/user';
import { list as organList } from '@/api/system/organ';
import { list as roleList } from '@/api/system/role';
import { passEncrypt } from '@/utils/rsa';
import DetailAction from '@/views/_mixins/detail-action';

export default {
  name: 'ItemDetail',
  mixins: [DetailAction],
  components: {
    TableRowDetailDialog,
    FormItemGroup,
  },
  props: {},
  data() {
    var checkName = async (rule, value, callback) => {
      this.nameCheck = false;
      if (value === '') {
        callback(new Error('名称必填'));
      } else {
        if (!this.nameFlag && this.dialogType === 'add') {
          this.nameFlag = true;
          let params = {
            userName: value,
          };
          await usernameValid(params).then((res) => {
            if (res.data) {
              this.nameCheck = true;
              callback();
            } else {
              this.nameCheck = false;
              callback(new Error('登录名已存在!'));
            }
          });
        }
      }
    };
    var checkTel = async (rule, value, callback) => {
      this.telCheck = false;
      if (value === '') {
        callback(new Error('手机号必填'));
      } else {
        let reg_tel = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
        if (!reg_tel.test(value)) {
          callback(new Error('手机号码格式有误'));
          return;
        }
        if (!this.telFlag) {
          this.telFlag = true;
          let params = null;
          if (this.dialogType === 'add') {
            params = {
              tel: value,
            };
          } else {
            params = {
              userId: this.userId,
              tel: value,
            };
          }
          await phoneValid(params).then((res) => {
            if (res.data) {
              this.telCheck = true;
              callback();
            } else {
              this.telCheck = false;
              callback(new Error('手机号已存在!'));
            }
          });
        }
      }
    };
    var checkPWD = async (rule, value, callback) => {
      if (value === '') {
        callback(new Error('密码必填'));
      } else {
        // 正则
        let reg =
          /^(?=.*[A-Za-z])(?=.*\d)(?=.*[`~!@#$%^&*()_+<>?:"{},.\/\\;'[\]])[A-Za-z\d`~!@#$%^&*()_+<>?:"{},.\/\\;'[\]]{8,}$/;
        // 可用 test 方法验证
        if (!reg.test(value)) {
          callback(new Error('至少8位且必有数字、特殊字符、字母'));
          return;
        }
        if (this.formData.repeatPass) {
          //js---触发单个校验
          this.$refs.form.validateField('repeatPass');
        }
      }
    };
    var checkRP = async (rule, value, callback) => {
      if (value === '') {
        callback(new Error('重复密码必填'));
        return;
      }
      if (this.formData.passwd === '') {
        //js---触发单个校验
        this.$refs.form.validateField('passwd');
        return;
      } else {
        if (this.formData.passwd !== value) {
          //js---触发单个校验
          callback(new Error('与设置密码不一致'));
        }
      }
    };
    return {
      organOption: [],
      roleOption: [],
      organProps: {
        value: 'organId',
        label: 'organName',
        emitPath: false,
      },
      nameCheck: false,
      nameFlag: false,
      copyName: '',
      telCheck: false,
      telFlag: false,
      userId: '',
      rules: {
        userName: [{ required: true, validator: checkName, trigger: 'blur' }],
        realName: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
        tel: [{ required: true, validator: checkTel, trigger: 'blur' }],
        passwd: [{ required: true, validator: checkPWD, trigger: 'blur' }],
        repeatPass: [
          {
            required: true,
            validator: checkRP,
            trigger: 'blur',
          },
        ],
      },
    };
  },
  // watch: {
  //   'formData.tel': function (val) {
  //     //单个数据验证
  //     if (val != undefined && val.length == 11) {
  //       this.validateField('tel');
  //     }
  //   },
  // },
  computed: {},
  created() {},
  methods: {
    //表单单项验证
    validateField(fieldName) {
      this.$refs.form.validateField(fieldName);
    },
    //初始化表单数据
    initFormData() {
      this.nameCheck = true;
      this.nameFlag = true;
      this.telCheck = true;
      this.telFlag = true;

      this.formData = {
        userName: '',
        realName: '',
        tel: '',
        passwd: '',
        repeatPass: '',
        organid: '',
        role: [],
        description: '',
        enable: 1,
      };
      if (this.dialogType !== 'add') {
        delete this.formData.passwd;
        delete this.formData.repeatPass;
      }
      this.getOrganTreeList();
      this.getRoleList();
    },
    getOrganTreeList() {
      organList().then((res) => {
        this.organOption = arrayToTree(res.rows, 'organId', 'preorganid');
      });
    },
    getRoleList() {
      roleList().then((res) => (this.roleOption = res.rows));
    },

    /**
     * 获取记录详情
     * 填充表单数据对象
     * */
    getDetail(data) {
      this.userId = data.userId;
      this.copyName = data.userName;
      detail(this.userId).then((res) => {
        for (let key in this.formData) {
          this.formData[key] = res[key] || '';
        }
      });
      userRoles(this.userId).then((res) => {
        this.formData.role = res.rows.map((item) => item.roleId);
      });
    },
    /**
     * 对话框确认按钮响应
     * */
    handleUserConfirm() {
      if (!this.nameCheck || !this.telCheck) {
        return false;
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.dialogType === 'add') {
            delete this.formData.repeatPass;
            this.submitAdd(this.formData);
          } else {
            this.submitEdit(this.formData);
          }
        } else {
          return false;
        }
      });
    },
    /**
     * 添加记录
     * 校验表单数据后，add接口
     */
    async submitAdd(data) {
      data.passwd = await passEncrypt(data.passwd);
      add(data).then((res) => {
        setUserRole(res.userId, data.role).then(this.submitSuccess);
      });
    },
    /**
     * 记录详情数据编辑提交
     * 校验表单数据后，调用edit接口
     */
    submitEdit(data) {
      edit(this.userId, data).then(this.submitSuccess);
      setUserRole(this.userId, data.role).then();
    },
    handleCancel() {
      this.$refs.detailDialog.hide();
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog-body {
}
</style>
